#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import time
import unittest

import xlsxwriter

from controller import check, sendMail as sd
from controller import apiCaseXml, excelReport as be
from controller import httpRequest
from model.common import Goals as go


class MyTestCase(unittest.TestCase):
    def __init__(self, testName, xmlfile,index=0,sendmail=0):
        super(MyTestCase, self).__init__('function')
        self.testName = testName
        self.xmlfile = xmlfile
        self.gm = apiCaseXml.ret_xml(xmlfile)  # 读取xml
        self.hb = apiCaseXml.ret_http_base(self.gm)  # 读取http参数
        self.index = index
        self.sendmail=sendmail

    def setUp(self):
        self.config_http = httpRequest.HttpRequest(self.hb.host, self.hb.port)

    def function(self):
        hope = self.gm[self.index]["hope"]  # 预期值
        response = ""
        try:
            if self.gm[self.index]["method"] == "POST":
                response = self.config_http.post(go.URL, go.PARAMS)
            if self.gm[self.index]["method"] == "GET":
                response = self.config_http.get(go.URL, go.PARAMS)
            if self.gm[self.index]["method"] == "BODY":
                response = self.config_http.postBody(go.URL, go.PARAMS)
        except:
            go.RESULT = 'Fail'
            go.REALLY_RESULT="bad requset"
            go.ERROR_NUM += 1
            go.CASE_TOTAL += 1
            return
        try:
            hope = json.loads(hope)
            go.REALLY_RESULT = json.loads(response)
            temp = check.compare(hope, go.REALLY_RESULT)
            if temp:
                go.RESULT = 'Pass'
                go.SUCCESS_SUM += 1
            else:
                go.RESULT = 'Fail'
                go.ERROR_NUM += 1
        except:
            go.REALLY_RESULT = response
            temp = check.compareStr(hope, go.REALLY_RESULT)
            if temp:
                go.RESULT = 'Pass'
                go.SUCCESS_SUM += 1
            else:
                go.RESULT = 'Fail'
                go.ERROR_NUM += 1
        go.CASE_TOTAL += 1



    def get_test_suite(self,index):
        test_suite = unittest.TestSuite()
        test_suite.addTest(MyTestCase( self.testName,self.xmlfile,index))
        return test_suite

    # 运行测试用例函数
    def get_run_case_data(self,runner):
        data = {"info": []}
        data["test_sum"] = go.CASE_TOTAL
        data["test_failed"] = go.ERROR_NUM
        data["test_version"] = "v2.0.8"
        data["test_pl"] = "python 3"
        data["test_net"] = "本地连接"
        data["test_name"] = self.gm[0]["title"]
        data["test_success"] = go.SUCCESS_SUM
        data["test_host"] = self.gm[0]["host"]
        data["test_port"] = self.gm[0]["port"]
        case_list = self.hb.No
        case_list = eval(case_list)  # 把字符串类型的list转换为list
        temp_case = ""
        if len(case_list) == False:  # 判断是否执行指定的用例ID
            temp_case = self.gm
            for index in range(1, len(temp_case)):
                info = {}
                go.URL = self.gm[index]['url']
                go.PARAMS = self.gm[index]["params"]
                test_suite = self.get_test_suite(index)
                runner.run(test_suite)
                # 记录运行结果
                info["t_id"] = self.gm[index]["id"]
                info["t_name"] = self.gm[index]["name"]
                info["t_url"] = self.gm[index]["url"]
                info["t_param"] = self.gm[index]["params"]
                info["t_actual"] = go.REALLY_RESULT
                info["t_hope"] = self.gm[index]["hope"]
                info["t_result"] = go.RESULT
                info["t_method"] = self.gm[index]["method"]
                data["info"].append(info)
        else:
            for i in case_list:
                for j in range(1, len(self.gm)):
                    if str(i) ==self.gm[j]['id']:
                        info = {}
                        go.URL = self.gm[j]['url']
                        go.PARAMS = self.gm[j]["params"]
                        test_suite = self.get_test_suite(j)
                        runner.run(test_suite)
                        info["t_id"] = self.gm[j]["id"]
                        info["t_name"] = self.gm[j]["name"]
                        info["t_url"] = self.gm[j]["url"]
                        info["t_param"] = self.gm[j]["params"]
                        info["t_actual"] = go.REALLY_RESULT
                        info["t_hope"] = self.gm[j]["hope"]
                        info["t_result"] = go.RESULT
                        info["t_method"] = self.gm[j]["method"]
                        data["info"].append(info)
        return data

    def export_excel(self,runner):
            start_time = time.time()
            data=self.get_run_case_data(runner)
            end_time = time.time()
            sum_time = "%.2f" % (end_time - start_time)
            data["test_date"] = str(sum_time) + "毫秒"
            workbook = xlsxwriter.Workbook(self.testName+'.xlsx')
            #worksheet = workbook.add_worksheet("测试总况")
            worksheet2 = workbook.add_worksheet("测试详情")
            bc = be.xlsxwriterBase(wd=workbook, data=data)
            #bc.init(worksheet)
            bc.test_detail(worksheet2)
            bc.close()
            if self.sendmail==1:
                sd.send_mail(self.testName+'.xlsx', ["liuwang@ppfuns.com"],self.testName+'接口测试结果','测试结果')

